﻿using Coldairarrow.Entity.BackStage.ConsumeChats;
using Coldairarrow.Entity.Base_AutoReplys;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.IBusiness;
using Coldairarrow.IBusiness.BTB_StaffUsers;
using Coldairarrow.Util;
using Coldairarrow.Util.DTO.OnlineChat;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Business.BTB_StaffUsers
{
    class CServiceOnlineChatBusiness : BaseBusiness<ChatRoom>, ICServiceOnlineChatBusiness, ITransientDependency
    {
        private readonly IHubContext<MessageHub> _messageHub;
        readonly string userDefaultHeadImg = "http://qnmzptapi.xazkrj.cn/Upload/HeadPort/dhead.jpg";
        readonly string KfDefaultHeadImg = "/HeadImg/kefu002.png";
        readonly string WGHUserName = "estore";
        readonly string WGHPassword = "estore123";
        readonly IOperator _operator;
        readonly IServiceProvider _serviceProvider;
        public CServiceOnlineChatBusiness(IDbAccessor db, IOperator @operator, IHubContext<MessageHub> messageHub, IServiceProvider serviceProvider)
           : base(db)
        {
            _serviceProvider = serviceProvider;
            _messageHub = messageHub;
            _operator = @operator;
        }


        /// <summary>
        /// 客服发送消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="BusException"></exception>
        public async Task CServiceSendMessageAsync(UserSendChatDTO input)
        {
            #region//获取房间信息
            var rModel = await Service.GetIQueryable<ChatRoom>().Where(m => m.Id.Equals(input.roomId)).FirstOrDefaultAsync();
            if (!rModel.IsNullOrEmpty())
            {
                string consumeServiceId = ""; //客服Id

                #region//获取在线客服信息
                GetRoomDTO res = new GetRoomDTO();
                List<OnLinkUserDTO> csList = new List<OnLinkUserDTO>();
                var cache = _serviceProvider.GetService<IDistributedCache>();
                var jstr = cache.GetString("OLinkUserList");
                if (!jstr.IsNullOrEmpty())
                {
                    csList = JsonConvert.DeserializeObject<List<OnLinkUserDTO>>(jstr);

                }
                else
                {
                    csList = new List<OnLinkUserDTO>();
                }

                List<string> uIds = csList.Where(m => m.UserType == 1 && m.Class == rModel.ClassId).Select(x => x.UserId).ToList();

                //获取客服列表
                List<CServiceDTO> cList = new List<CServiceDTO>();
                var cstr = cache.GetString("OCSUserList");
                if (!jstr.IsNullOrEmpty())
                {
                    cList = JsonConvert.DeserializeObject<List<CServiceDTO>>(jstr);
                }
                else
                {
                    cList = new List<CServiceDTO>();
                }
                #endregion

                #region//获取房间客服信息
                var csmModel = await (from a in Service.GetIQueryable<ChatRoom>().Where(m => m.Id.Equals(input.roomId))
                               join b in Service.GetIQueryable<ChatRoomCSUser>().Where(m => m.State == true) on a.Id equals b.RoomId
                               join j in Service.GetIQueryable<ConsumeServer>().Where(h => h.ClassId == rModel.ClassId) on b.ConstmeServerId equals j.UserId
                               join k in Service.GetIQueryable<Base_User>() on j.UserId equals k.Id
                               select k).FirstOrDefaultAsync();

                if (!csList.IsNullOrEmpty() && csmModel.Id == _operator.UserId)
                {
                    consumeServiceId = _operator.UserId;

                }
                else
                {
                    throw new BusException("您不是此房间客服，无法发送消息！");
                }
                #endregion

                #region//向用户发送用户消息
                //向客服发送消息
                ChatContent scModel = new ChatContent();
                scModel.Id = IdHelper.GetId();
                scModel.CreatorId = "";
                scModel.CreateTime = DateTime.Now;
                scModel.Deleted = false;
                scModel.MessageType = input.messageType;
                scModel.MessageContent = input.messageContent;
                scModel.RoomId = input.roomId;
                scModel.ReadState = false;
                scModel.SenderId = _operator.UserId;
                scModel.ReceiverId = rModel.UserId;
                scModel.SenderType = 1;
                scModel.MassageName = input.messageName;
                scModel.MessageSize = input.messageSize;
                scModel.VState = input.vstate;

                await Service.InsertAsync(scModel);


                #endregion


                //刷新用户房间消息列表
                await UpdateCUMessageList(rModel.UserId, rModel.ClassId, rModel.Id);

                //更新用户未读消息数量
                await SendCUnReadNum(rModel.UserId, rModel.ClassId, input.roomId);

                //更新客服消息为已读
                await Service.UpdateAsync<ChatContent>(x => x.ReceiverId.Equals(consumeServiceId) && x.RoomId.Equals(rModel.Id) && x.ReadState == false, m => m.ReadState = true);

                //更新客服已读消息数量
                await SendCSUnReadNum(consumeServiceId, rModel.ClassId);

                //刷新客服房间列表
                await UpdateCSRoomList(consumeServiceId, rModel.ClassId);

            }
            else
            {
                throw new BusException("获取房间失败，发送消息失败！");
            }

            #endregion

        }

        /// <summary>
        /// 获取房间用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<object> GetRoomUserInfoAsync(IdInputDTO input)
        {
            var res = new object();
            var rModel = await Service.GetIQueryable<ChatRoom>().Where(m => m.Id.Equals(input.Id)).FirstOrDefaultAsync();
            if (!rModel.IsNullOrEmpty())
            {
                var userId = rModel.UserId;
                var uMdoel = await Service.GetIQueryable<BTB_StaffUser>().Where(s => s.id.Equals(rModel.UserId)).FirstOrDefaultAsync();
                if (uMdoel.IsNullOrEmpty())
                {
                    res = new
                    {
                        Name = "游客"+ userId.Substring(userId.Length - 6),
                        HeadImg = userDefaultHeadImg,
                        HeadType = 1,
                        Sex = 0,
                        Phone = ""
                    };
                }
                else
                {
                    res = new
                    {
                        Name = uMdoel.NickName,
                        HeadImg = uMdoel.HeadPortrait.IsNullOrEmpty()? userDefaultHeadImg : uMdoel.HeadPortrait,
                        HeadType = uMdoel.HeadPortrait.IsNullOrEmpty()? 1 : uMdoel.HeadType ,
                        Sex = uMdoel.Sex,
                        Phone = uMdoel.phone
                    };
                }

                return res;
            }
            else
            {
                throw new BusException("查询房间信息为空，查询失败！");
            }
        }

        /// <summary>
        /// 客服获取未读消息数量
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="BusException"></exception>
        public async Task UserGetUnReadCountAsync(ClassIdDTO input)
        {
            string userId = _operator.UserId;

            await SendCSUnReadNum(userId, input.ClassId);

        }

        /// <summary>
        /// 发送用户未读订单消息数量
        /// </summary>
        /// <param name="uIds"></param>
        /// <param name="count"></param>
        /// <param name="checkStr"></param>
        /// <returns></returns>
        /// <exception cref="BusException"></exception>
        public async Task GetUserNewOrderCountAsync(List<string> uIds, int count, string checkStr)
        {
            try
            {
                checkStr = AESHelper.AesDecrypt(checkStr);
                var resData = JsonConvert.DeserializeObject<CheckDTO>(checkStr);
                if (resData != null)
                {
                    if (!resData.UserName.Equals(WGHUserName) || !resData.PassWord.Equals(WGHPassword) || !(resData.Time.AddMinutes(3) > DateTime.Now))
                    {
                        Log.Information("平台账号密码错误请重试！");
                        throw new BusException("身份验证失败请重试！");
                    }
                }
                else
                {
                    Log.Information("验签验证失败请重试！");
                    throw new BusException("验签验证失败请重试！");
                }
            }
            catch
            {
                Log.Information("验签验证失败请重试！");
                throw new BusException("验签验证失败请重试！");
            }


            foreach (var item in uIds)
            {
                await _messageHub.Clients.Groups("CS" + item).SendAsync("NewOrderCount", count);
            }
        }


        /// <summary>
        /// 客服获取聊天记录列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ChatLogListDTO> GetCServiceMessageLogAsync(GetMassageDTO input)
        {
            ChatLogListDTO res = new ChatLogListDTO();
            Log.Information("进入获取聊天记录列表");
            ChatLogListDTO data = new ChatLogListDTO();
       
            var  userId = _operator.UserId;

            //获取客服列表
            var cache = _serviceProvider.GetService<IDistributedCache>();
            List<CServiceDTO> cList = new List<CServiceDTO>();
            var cstr = cache.GetString("OCSUserList");
            if (!cstr.IsNullOrEmpty() && cstr.Contains("["))
            {
                cList = JsonConvert.DeserializeObject<List<CServiceDTO>>(cstr);
            }
            else
            {
                cList = new List<CServiceDTO>();
            }

            if (!userId.IsNullOrEmpty() && !input.roomId.IsNullOrEmpty())
            {
                Log.Information("记录列表 userId = " + userId);
                var rModel = Service.GetIQueryable<ChatRoom>().Where(m => m.Id.Equals(input.roomId)).FirstOrDefault();
                if (!rModel.IsNullOrEmpty())
                {
                    DateTime StartTime = new DateTime();
                    if (input.stime.HasValue)
                    {
                        StartTime = input.stime.Value;
                    }
                    else
                    {
                        StartTime = DateTime.Now;
                    }

                    #region//初始参数配置
                    if (input.page <= 0)
                    {
                        input.page = 1;
                    }

                    if (input.row <= 0)
                    {
                        input.row = 10;
                    }
                    #endregion

                    res.MCount = Service.GetIQueryable<ChatContent>().Where(m => ((m.MessageType == 10 && m.ReceiverId.Equals(_operator.UserId)) || m.MessageType != 10)&&  m.RoomId.Equals(input.roomId) && m.CreateTime <= StartTime).Count();

                    //获取消息记录
                    var msList = Service.GetIQueryable<ChatContent>().Where(m => ((m.MessageType == 10 && m.ReceiverId.Equals(_operator.UserId)) || m.MessageType != 10)&&  m.RoomId.Equals(input.roomId) && m.CreateTime <= StartTime).OrderByDescending(m => m.CreateTime).Skip(input.row * (input.page - 1)).Take(input.row).ToList();

                    //获取客服信息
                    var csMdoel = await (from a in Service.GetIQueryable<Base_User>().Where(x => x.Id.Equals(userId))
                                         join b in Service.GetIQueryable<ConsumeServer>() on a.Id equals b.UserId into ab
                                         from b in ab.DefaultIfEmpty()
                                         select new
                                         {
                                             a.Id,
                                             a.RealName,
                                             b.HeadImg,
                                             HeadType = 0
                                         }).FirstOrDefaultAsync();

                    res.MList = new List<ChatLogDTO>();
                    foreach (var item in msList)
                    {
                        ChatLogDTO mModel = new ChatLogDTO();
                        mModel.Id = item.Id;
                        mModel.createTime = item.CreateTime;
                        mModel.createTimes = mModel.createTime.ToString("yyyy年MM月dd日 HH:mm:ss");
                        if (item.SenderType == 0)
                        {
                            mModel.userType  = item.SenderType;
                            var uModel = await Service.GetIQueryable<BTB_StaffUser>().Where(m => m.id.Equals(item.SenderId)).FirstOrDefaultAsync();
                            if (uModel != null)
                            {
                                mModel.headPortrait = uModel.HeadPortrait.IsNullOrEmpty() ? userDefaultHeadImg : uModel.HeadPortrait;
                                mModel.headImgType = uModel.HeadPortrait.IsNullOrEmpty() ? 1 : uModel.HeadType ;
                                mModel.nickName = uModel.NickName;
                                mModel.nickNames = uModel.NickName;
                            }
                            else
                            {
                                mModel.headPortrait = userDefaultHeadImg;
                                mModel.headImgType = 0;
                                mModel.nickName = "游客" + item.SenderId.Substring(item.SenderId.Length - 5);
                                mModel.nickNames ="游客" + item.SenderId.Substring(item.SenderId.Length - 5);
                            }

                        }
                        else
                        {
                            mModel.userType  =  item.SenderType;

                            if (!csMdoel.IsNullOrEmpty())
                            {
                                string sPath = GetServicePath();
                                mModel.headPortrait =sPath + "/" + (csMdoel.HeadImg.IsNullOrEmpty()?  KfDefaultHeadImg : csMdoel.HeadImg);
                                mModel.headImgType = 1;
                                mModel.nickName = csMdoel.RealName;
                                mModel.nickNames = csMdoel.RealName;
                            }
                            else
                            {
                                string sPath = GetServicePath();
                                mModel.headPortrait = sPath + "/" + KfDefaultHeadImg;
                                mModel.headImgType = 1;
                                mModel.nickName = "客服" + userId.Substring(userId.Length - 5);
                                mModel.nickNames ="客服" + userId.Substring(userId.Length - 5);
                            }
                        }

                        mModel.messageContent = item.MessageContent;
                        mModel.messageType = item.MessageType;

                        //自动回复整理内容
                        if (mModel.messageType == 11 && !item.MessageContent.IsNullOrEmpty())
                        {
                            var rpModel = (from a in Service.GetIQueryable<Base_AutoReply>().Where(s => s.Id.Equals(item.MessageContent))
                                           select new AutoReplyDTO
                                           {
                                               id = a.Id,
                                               contents = a.Contents,
                                               imgURL = a.ImgURL,
                                               link = a.ImgURL,
                                               childList = (from b in Service.GetIQueryable<Base_AutoReplyDetail>(true).Where(s => s.ReplyId.Equals(a.Id))
                                                            select new ReplyDetailDTO
                                                            {
                                                                id = b.Id,
                                                                contents = b.KeyNum,
                                                                imgURL = b.ImgUrl,
                                                                link = b.LinkUrl
                                                            }).ToList()
                                           }).FirstOrDefault();
                            if (!rpModel.IsNullOrEmpty())
                            {
                                mModel.auto_Model = rpModel;
                            }


                        }
                        else if (mModel.messageType == 12 && !item.MessageContent.IsNullOrEmpty())
                        {
                            var dtMdoel = Service.GetIQueryable<Base_AutoReplyDetail>().Where(x => x.Id.Equals(item.MessageContent)).Select(s => new Base_AutoReplyDetailDTO
                            {
                                id = s.Id,
                                createTime = s.CreateTime,
                                replyId = s.ReplyId,
                                contents = s.Contents
                            }).FirstOrDefault();
                            if (!dtMdoel.IsNullOrEmpty())
                            {
                                mModel.detailModel = dtMdoel;
                            }
                            else
                            {
                                mModel.messageType = 1;
                                mModel.messageContent = "抱歉，未找到对应内容";
                                Service.Update(mModel);
                            }
                        }
                      
                        mModel.messageSize = item.MessageSize;
                        mModel.messageName = item.MassageName;
                        mModel.vstate = item.VState;

                        res.MList.Add(mModel);

                        //修改未读为已读
                        if (item.ReadState == false && item.ReceiverId.Equals(userId))
                        {
                            item.ReadState = true;
                            await Service.UpdateAsync(item);
                        }
                    }

                    await UpdateCUMessageList(userId,rModel.ClassId,rModel.Id);

                    var rcsModel = cList.Where(m => m.Id.Equals(userId) && m.ClassId.Equals(rModel.ClassId)).FirstOrDefault();
                    if (rcsModel.IsNullOrEmpty())
                    {
                        CServiceDTO rcModel = new CServiceDTO();
                        rcModel.Id = userId;
                        rcModel.ClassId = rModel.ClassId;
                        rcModel.OnChatRoomId = rModel.Id;

                        cList.Add(rcModel);
                        cache.SetString("OCSUserList", cList.ToJson().ToString());
                    }
                    else
                    {
                        //判断当前聊天人是否此用户
                        if (!rcsModel.OnChatRoomId.Equals(rModel.Id))
                        {
                            //插入新客服
                            rcsModel.OnChatRoomId = rModel.Id;
                            cache.SetString("OCSUserList", cList.ToJson().ToString());
                        }
                    }
                }
                else
                {
                    res.MCount = 0;
                    res.MList = new List<ChatLogDTO>();
                }


               
            }
            else
            {
                res.MCount = 0;
                res.MList = new List<ChatLogDTO>();
            }

           

            return res;
        }

        /// <summary>
        /// 客服——动态刷新客服房间列表
        /// </summary>
        /// <returns></returns>
        public async Task UpdateRoomListAsync(int classId)
        {
            await UpdateCSRoomList(_operator.UserId, classId);
        }

        /// <summary>
        /// 后台——客服用户房间列表删除用户
        /// </summary>
        /// <param name="roomId"></param>
        /// <returns></returns>
        public async Task DelRoomAsync(string roomId)
        {
            var rModel = Service.GetIQueryable<ChatRoom>().Where(m => m.Id.Equals(roomId)).FirstOrDefault();
            if (!rModel.IsNullOrEmpty())
            {
                var sModel = await Service.GetIQueryable<ChatRoomCSUser>().Where(n => n.RoomId.Equals(roomId) && n.ConstmeServerId.Equals(_operator.UserId)).OrderByDescending(s => s.CreateTime).FirstOrDefaultAsync();
                if (!sModel.IsNullOrEmpty() && sModel.State == true)
                {
                    sModel.State = false;
                    sModel.EndTime = DateTime.Now;
                    await Service.UpdateAsync(sModel);

                    //更新客服消息为已读
                    await Service.UpdateAsync<ChatContent>(x => x.ReceiverId.Equals(_operator.UserId) && x.RoomId.Equals(rModel.Id) && x.ReadState == false, m => m.ReadState = true);

                    //更新客服已读消息数量
                    await SendCSUnReadNum(_operator.UserId, rModel.ClassId);

                    //刷新客服房间列表
                    await UpdateCSRoomList(_operator.UserId, rModel.ClassId);
                }
                else
                {
                    throw new BusException("未查询到此房间，移除失败！");
                }
            }
            else
            {
                throw new BusException("获取房间失败，移除失败！");
            }
        }

        #region//私有方法

        /// <summary>
        /// 刷新客服未读消息数量
        /// </summary>
        private  async Task  SendCSUnReadNum(string CSUserId,int ClassId)
        {
            //判断用户是否客服
            var aCount = Service.GetIQueryable<ConsumeServer>().Where(s => s.UserId.Equals(CSUserId)  && ClassId > -1 && s.State == true).Count();
            if (aCount > 0)
            {
                //获取房间未读消息
                int uReadCount = (from a in Service.GetIQueryable<ChatContent>().Where(m => m.ReceiverId.Equals(CSUserId) && m.ReadState == false)
                                  join b in Service.GetIQueryable<ChatRoom>().Where(m => m.ClassId.Equals(ClassId)) on a.RoomId equals b.Id
                                  select a).Count();

                Log.Information("SendCSUnReadNum=>uReadCount:{0}", uReadCount);
                await _messageHub.Clients.Groups("CS" + CSUserId).SendAsync("UserUnread", uReadCount);
            }
            else
            {
                await _messageHub.Clients.Groups("CS" + CSUserId).SendAsync("UserUnread", -1);
            }
        }

       /// <summary>
       /// 刷新客服房间列表
       /// </summary>
       /// <param name="CSUserId"></param>
       /// <param name="ClassId"></param>
       /// <returns></returns>
        private async Task UpdateCSRoomList(string CSUserId, int ClassId)
        {
            
            var list = await (from a in Service.GetIQueryable<ConsumeServer>().Where(h => h.ClassId == ClassId && h.UserId.Equals(CSUserId))
                        join k in Service.GetIQueryable<ChatRoomCSUser>().Where(m => m.State == true) on a.UserId equals k.ConstmeServerId
                        join b in Service.GetIQueryable<ChatRoom>().Where(x => x.ClassId == ClassId) on k.RoomId equals b.Id
                        join c in Service.GetIQueryable<BTB_StaffUser>() on b.UserId equals c.id into bc
                        from c in bc.DefaultIfEmpty()
                        select new { 
                            RId = b.Id,
                            RName = b.ChatRoot_Name,
                            UId = b.UserId,
                            UHeadImg = c.HeadPortrait,
                            UheadType = c.HeadType,
                            UName = c.NickName 
                        }).ToListAsync();

            List<SRoomDTO> dList = new List<SRoomDTO>();
            foreach (var item in list)
            {
                SRoomDTO rModel = new SRoomDTO();
                rModel.RoomId = item.RId;
                if (item.UName.IsNullOrEmpty())
                {
                    rModel.UserId = "USE" + item.UId;
                    rModel.RoomName = "游客"+item.UId.Substring(item.UId.Length - 5);
                    rModel.HeadType = 1;
                    rModel.HeadImg = userDefaultHeadImg;
                }
                else
                {
                    rModel.UserId = "USE" + item.UId;
                    rModel.RoomName = item.UName;
                    rModel.HeadImg = item.UHeadImg.IsNullOrEmpty() ? userDefaultHeadImg : item.UHeadImg;
                    rModel.HeadType =item.UHeadImg.IsNullOrEmpty() ? 1 : item.UheadType;
                   
                }

                //获取房间最新消息
                var message = await Service.GetIQueryable<ChatContent>().Where(x => x.RoomId.Equals(item.RId)).OrderByDescending(m => m.CreateTime).FirstOrDefaultAsync();
                if(!message.IsNullOrEmpty())
                {
                    rModel.MSTime = message.CreateTime;
                    rModel.messageType = message.MessageType;
                    rModel.NewMassage = message.MessageContent;
                    if (rModel.messageType == 12 || rModel.messageType == 11)
                    {
                        rModel.NewMassage ="[自动回复]";
                    }
                }

                //获取房间客服未读消息数量
                rModel.MSCount =  Service.GetIQueryable<ChatContent>().Where(x => x.RoomId.Equals(item.RId) && x.ReadState == false && x.ReceiverId.Equals(CSUserId)).Count();
                dList.Add(rModel);
            }

            dList = dList.OrderByDescending(x => x.MSTime).ToList();
            Log.Information("SendCSUnReadNum=>dList:{0}", dList.Count);
            await _messageHub.Clients.Groups("CS" + CSUserId).SendAsync("StaffRoomList", dList);
        }

        /// <summary>
        /// 刷新用户未读消息数量
        /// </summary>
        private async Task SendCUnReadNum(string UserId, int ClassId, string RoomId)
        {
            //获取房间未读消息
            int uReadCount = (from a in Service.GetIQueryable<ChatContent>().Where(m => m.ReceiverId.Equals(UserId) && m.ReadState == false)
                              join b in Service.GetIQueryable<ChatRoom>().Where(m => m.ClassId.Equals(ClassId) && m.Id.Equals(RoomId) ) on a.RoomId equals b.Id
                              select a).Count();

            Log.Information("SendCUnReadNum=>uReadCount:{0}", uReadCount);
            await _messageHub.Clients.Groups("USE" + UserId).SendAsync("UserUnread", uReadCount);
        }

        /// <summary>
        /// 刷新用户房间未读消息列表
        /// </summary>
        /// <returns></returns>
        private async Task UpdateCUMessageList(string UserId, int ClassId, string RoomId)
        {
            TMessageDTO res = new TMessageDTO();
            res.MList = new List<SMessageDTO>();
            if (!RoomId.IsNullOrEmpty())
            {
                #region//获取所有未读消息
                var list = await (from b in Service.GetIQueryable<ChatRoom>().Where(x => x.ClassId == ClassId && x.Id.Equals(RoomId))
                                  join k in Service.GetIQueryable<ChatRoomCSUser>().Where(m => m.State == true) on b.Id equals k.RoomId
                                  join a in Service.GetIQueryable<ConsumeServer>().Where(h => h.ClassId == ClassId) on k.ConstmeServerId equals a.UserId
                                  join c in Service.GetIQueryable<Base_User>() on a.UserId equals c.Id
                                  join d in Service.GetIQueryable<ChatContent>().Where(x => x.ReadState == false && x.ReceiverId.Equals(UserId)) on b.Id equals d.RoomId
                                  select new
                                  {
                                      RId = b.Id,
                                      RName = b.ChatRoot_Name,
                                      UId = c.Id,
                                      UHeadImg = a.HeadImg,
                                      UheadType = 0,
                                      UName = c.RealName,
                                      d.Id,
                                      d.CreateTime,
                                      d.MessageType,
                                      d.MassageName,
                                      d.MessageContent,
                                      d.VState,
                                      d.MessageSize,
                                  }).OrderByDescending(m => m.CreateTime).Take(1).ToListAsync();

                if (list.Count > 0)
                {
                    res.STime = list[0].CreateTime;

                    foreach (var item in list)
                    {
                        string sPath = GetServicePath();
                        SMessageDTO MDTO = new SMessageDTO();
                        MDTO.Id = item.Id;
                        MDTO.userType = 1;
                        MDTO.nickName  = item.UName;
                        MDTO.headType = 1;
                        MDTO.headPortrait = sPath +"/"+( item.UHeadImg.IsNullOrEmpty() ? KfDefaultHeadImg : item.UHeadImg);
                        MDTO.messageType = item.MessageType;
                        MDTO.messageContent = item.MessageContent;
                        //自动回复整理内容
                        if (MDTO.messageType == 11 && !item.MessageContent.IsNullOrEmpty())
                        {
                            var rpModel = (from a in Service.GetIQueryable<Base_AutoReply>().Where(s => s.Id.Equals(item.MessageContent))
                                           select new AutoReplyDTO
                                           {
                                               id = a.Id,
                                               contents = a.Contents,
                                               imgURL = a.ImgURL,
                                               link = a.ImgURL,
                                               childList = (from b in Service.GetIQueryable<Base_AutoReplyDetail>(true).Where(s => s.ReplyId.Equals(a.Id))
                                                            select new ReplyDetailDTO
                                                            {
                                                                id = b.Id,
                                                                contents = b.KeyNum,
                                                                imgURL = b.ImgUrl,
                                                                link = b.LinkUrl
                                                            }).ToList()
                                           }).FirstOrDefault();
                            if (!rpModel.IsNullOrEmpty())
                            {
                                MDTO.auto_Model = rpModel;
                            }

                        }
                        else if (MDTO.messageType == 12 && !item.MessageContent.IsNullOrEmpty())
                        {
                            var dtMdoel = Service.GetIQueryable<Base_AutoReplyDetail>().Where(x => x.Id.Equals(item.MessageContent)).Select(s => new Base_AutoReplyDetailDTOs
                            {
                                id = s.Id,
                                createTime = s.CreateTime,
                                replyId = s.ReplyId,
                                contents = s.Contents
                            }).FirstOrDefault();
                            if (!dtMdoel.IsNullOrEmpty())
                            {
                                MDTO.detailModel = dtMdoel;
                            }
                            else
                            {
                                MDTO.messageType = 1;
                                MDTO.messageContent = "抱歉，未找到对应内容";
                                Service.Update(MDTO);
                            }
                        }

                        MDTO.createTime = item.CreateTime;
                        MDTO.createTimes =  MDTO.createTime.ToString("yyyy年MM月dd日 HH:mm:ss");
                        MDTO.MessageName =  item.MassageName;
                        MDTO.MessageSize = item.MessageSize;
                        MDTO.vstate = item.VState;

                        res.MList.Add(MDTO);
                    }

                }
                else
                {
                    res.STime = DateTime.Now;
                }

                #endregion
            }

            Log.Information("SendCSUnReadNum=>res:{0}", res.MList.Count);
            await _messageHub.Clients.Groups("USE" + UserId).SendAsync("OnMessage", res);
        }
        #endregion

        /// <summary>
        /// 获取网站部署地址
        /// </summary>
        /// <returns></returns>
        private string GetServicePath()
        {
            var sPath =  ConfigurationUtil.GetSection("ServiceURL");

            return sPath;
        }
    }
}
